package com.hmjk.health.user;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.Rotate3dAnimation;
import com.hmjk.health.views.RoundImageView;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class UserDetailActivity extends Activity implements OnClickListener{
	private final String TAG = UserDetailActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private EditText mNick;
	private Button mButton;
	private boolean editMode = false;
	private Rotate3dAnimation mAnim1;
	private Rotate3dAnimation mAnim2;
	private Spinner mGender;
	//private EditText mCity;
	private EditText mAddress;
	private Spinner mEducation;
	private RoundImageView mPic;
	private TextView mAccount;
	private TextView mPhone;
	private View mCard;
	private boolean animPlaying = false;
	private JSONObject mData;
	private String refreshing = null;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		setContentView(R.layout.userdetail_activity);
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		mPic = (RoundImageView) findViewById(R.id.photo);
		mPic.setOnClickListener(this);
		
		mAccount = (TextView) findViewById(R.id.account);
		mPhone = (TextView) findViewById(R.id.phone);
		mButton = (Button)findViewById(R.id.commit);
		mButton.setOnClickListener(this);
		mButton.setText(R.string.edit);
		mCard = findViewById(R.id.card);
		editMode = false;
		mNick = (EditText)findViewById(R.id.nickedit);
		mGender = (Spinner)findViewById(R.id.spinnergender);
		//mCity = (EditText)findViewById(R.id.cityedit);
		
		mAddress = (EditText)findViewById(R.id.addredit);
		mEducation = (Spinner)findViewById(R.id.spinneredu);
		
		String genderArray[] = getResources().getStringArray(R.array.genderarray);
		ArrayAdapter<String> adapterGender = new ArrayAdapter<String>(this, R.layout.spinner_item, genderArray);
		adapterGender.setDropDownViewResource(R.layout.spinner_item);
		mGender.setAdapter(adapterGender);
		
		String educArray[] = getResources().getStringArray(R.array.educarray);
		ArrayAdapter<String> adapterEduc = new ArrayAdapter<String>(this, R.layout.spinner_item, educArray);
		adapterEduc.setDropDownViewResource(R.layout.spinner_item);
		mEducation.setAdapter(adapterEduc);
		
		editorEnable(mNick, false);
		//editorEnable(mCity, false);
		mGender.setEnabled(false);
		//mCity.setClickable(false);
		editorEnable(mAddress, false);
		mEducation.setEnabled(false);
	}
	
	private void editorEnable(final View v,final Boolean enable){
		if(enable){
			v.setEnabled(true);
			v.setBackgroundColor(0xFFEEEEEE);
		}else{
			v.setEnabled(false);
			v.setBackgroundColor(0xFFFFFFFF);
		}
	}
	
	private void enterEditMode(boolean anim){
		if(anim == false){
			if(editMode){
				mButton.setText(R.string.commit);
			}else{
				mButton.setText(R.string.edit);
				updateCard();
			}
			
			editorEnable(mNick, editMode);
			//editorEnable(mCity, editMode);
			mGender.setEnabled(editMode);
			//mCity.setClickable(editMode);
			editorEnable(mAddress, editMode);
			mEducation.setEnabled(editMode);
			return;
		}
		int w = mCard.getMeasuredWidth();
		int h = mCard.getMeasuredHeight();
		float x = w/2.0f;
		float y = h/2.0f;
		animPlaying = true;
		if(mAnim1 == null){
			mAnim1 = new Rotate3dAnimation("y",0,-90,x,y,0.1f,true);
			mAnim1.setDuration(200);
			mAnim1.setFillAfter(true);
			mAnim1.setInterpolator(new AccelerateInterpolator());
			mAnim1.setAnimationListener(new AnimationListener(){
				@Override
				public void onAnimationEnd(Animation arg0) {
					if(editMode){
						mButton.setText(R.string.commit);
					}else{
						mButton.setText(R.string.edit);
						updateCard();
					}
					
					editorEnable(mNick, editMode);
					//editorEnable(mCity, editMode);
					mGender.setEnabled(editMode);
					//mCity.setClickable(editMode);
					editorEnable(mAddress, editMode);
					mEducation.setEnabled(editMode);
					
					mCard.startAnimation(mAnim2);
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
				}
				@Override
				public void onAnimationStart(Animation arg0) {	
				}
				
			});
		}
		if(mAnim2 == null){
			mAnim2 = new Rotate3dAnimation("y",90,0,x,y,0.1f,true);
			mAnim2.setDuration(200);
			mAnim2.setFillAfter(true);
			mAnim2.setInterpolator(new AccelerateInterpolator());
			mAnim2.setAnimationListener(new AnimationListener(){

				@Override
				public void onAnimationEnd(Animation arg0) {
					animPlaying = false;
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {	
				}
				@Override
				public void onAnimationStart(Animation arg0) {
				}
			});
		}
		mCard.startAnimation(mAnim1);
	}
	
	private void updateCard(){
		try {
		String nick = mData.getString("nick");
		if(nick == null)
			mNick.setText("");
		else
			mNick.setText(nick);
		
		String gender = mData.getString("gender");
		if(gender.equalsIgnoreCase("M") || gender.equalsIgnoreCase("U")){
			mGender.setSelection(0);
		}else{
			mGender.setSelection(1);
		}
		
		String city = mData.getString("city");
		//mCity.setText(city);
		
		String addr = mData.getString("addr");
		mAddress.setText(addr);
		
		String edu = mData.getString("edu");
		if(edu.trim().isEmpty())
			edu = "3";
		
		int iedu = Integer.parseInt(edu);
		if(iedu > 6)
			iedu = 6;
		else if(iedu  < 1)
			iedu = 1;
		
		mEducation.setSelection(iedu -1);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void updatePhoto(){
		Bitmap bitmap = (Bitmap) mApp.getDataManager().checkData(DataManager.F_USERFACE, null);
		if((bitmap != null) && !bitmap.isRecycled()){
			mPic.setImageBitmap(bitmap);
			mPic.setType(RoundImageView.TYPE_ROUND);
			mPic.setBackgroundColor(getResources().getColor(R.color.TRANSPARENT));
		}else{
			mPic.setImageResource(R.drawable.default_photo);
			mPic.setType(RoundImageView.TYPE_RECT);
			mPic.setBackgroundResource(R.drawable.photo_bg);
		}
	}
	
	private void updateViews(){
		if((mCard == null) || (mApp == null))
			return;
		
		if(mData != null){
			updatePhoto();
			try {
				
				String ac = mData.getString("ac");
				if(ac.isEmpty()){
					ac = mApp.getUserName();
					if(mApp.isMobileNumber(ac)){
						ac = mApp.numberToHidenString(ac);
					}
				}
				mAccount.setText(ac);
				
				String mobile = mData.getString("mobile");
				mobile = mApp.numberToHidenString(mobile);
				String showmobile = getResources().getString(R.string.phonenumas, mobile);
				mPhone.setText(showmobile);
				
				updateCard();
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private void retrieveData(){
		mData = (JSONObject) mApp.getDataManager().checkData(DataManager.F_USERDATA, null);
	}
	
	private void refreshData(){
		refreshing = null;
		boolean ok = mApp.getDataManager().refreshData(DataManager.F_USERDATA);
		if(ok){
			refreshing = new String(DataManager.F_USERDATA);
		}
		ok = mApp.getDataManager().refreshData(DataManager.F_USERFACE);
		if(ok){
			if(refreshing == null)
				refreshing = new String(DataManager.F_USERFACE);
			else
				refreshing += ":" + DataManager.F_USERFACE;
		}
		
		logd("refreshData refreshing = "+ refreshing);
		if(refreshing != null){
			mApp.showWaitting(this, new OnCancelListener(){

				@Override
				public void onCancel(DialogInterface arg0) {
					if(refreshing != null){
						refreshing = null;
					}
				}
				
			});
		}
	}
	
	private void updateRefreshFlag(String clear){
		if(refreshing.contains(clear)){
			String[] ss = refreshing.split(":");
			String flag = "";
			for(String s:ss){
				if(s.equalsIgnoreCase(clear) == false){
					if(flag.equals("") == false){
						flag += ":";
					}
					flag += s;
				}
			}
			if(flag.trim().isEmpty())
				refreshing = null;
			else{
				refreshing = flag.trim();
			}
		}
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(HealthApp.ACTION_SIGN_IN_OUT)){
				boolean in = intent.getBooleanExtra("state", false);
				if(in == false){
					if(mApp.isUserSignIn()){
						Toast.makeText(UserDetailActivity.this, R.string.network_err, Toast.LENGTH_LONG).show();
					}
				}
			}else if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				boolean s = intent.getBooleanExtra("state", false);
				logd("onReceive:"+t+";"+s);
				if(t.equals(DataManager.F_USERDATA) || t.equals(DataManager.F_USERFACE)){
					if(refreshing != null){
						updateRefreshFlag(t);
						if(refreshing == null){
							mApp.dismissWaiting();
							retrieveData();
							updateViews();
						}
					}else if(s){
						retrieveData();
						updateViews();
					}
				}
			}else if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				String t = intent.getStringExtra("type");
				if(t.equals(DataManager.F_USERDATA)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					mApp.dismissWaiting();
					if(code != 200){
						mApp.showAlertDialog(UserDetailActivity.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.showAlertDialog(UserDetailActivity.this, R.string.commit_err);
					}else{
						finish();
					}
				}else if(t.equals(DataManager.F_USERFACE)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					
					if(code != 200){
						mApp.dismissWaiting();
						mApp.showAlertDialog(UserDetailActivity.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.dismissWaiting();
						mApp.showAlertDialog(UserDetailActivity.this, R.string.commit_err);
					}else{
						mApp.dismissWaiting();
						updatePhoto();
						if(editMode){
						editMode = false;
						enterEditMode(false);
						}
					}
				}
			}
		}
	};
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(HealthApp.ACTION_SIGN_IN_OUT);
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);
		if(editMode == false){
			retrieveData();
			updateViews();
			refreshData();
		}
	}
	
	@Override
	public void onPause(){
		super.onPause();
		logd("onPause");
		unregisterReceiver(mReceiver);
		mApp.dismissWaiting();
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
	   	
	   	if(keyCode == KeyEvent.KEYCODE_BACK){
	   		if(animPlaying)
	   			return true;
	   		
	   		if(editMode){
	   			quitEditConfirmation();
				return true;
	   		}
	   	}
	   	return super.onKeyDown(keyCode,event);
    }
	
	private void quitEditConfirmation(){
		String msg = getResources().getString(R.string.quitedit);
		mApp.showConfirmDialog(this, msg, new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				if(v.getId() == R.id.alert_but1){
					editMode = false;
					//enterEditMode(true);
					finish();
				}
			}
			
		});
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.photo:{
			mApp.showPickPhotoWin(this, new OnClickListener(){

				@Override
				public void onClick(View v) {
					if(v.getId() == R.id.pick_cam){
						String path = mApp.getUploadFacePreCropFileName();
						if(path == null)
							return;
						Uri imageUri = Uri.parse("file://" + path);
						Intent takephoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						takephoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						startActivityForResult(takephoto,RESULT_CODE_CAMERA);
					}else if(v.getId() == R.id.pick_album){
						String path = mApp.getUploadFaceFileName();
						if(path == null)
							return;
						Uri imageUri = Uri.parse("file://" + path);
						Intent cropAlbum = new Intent(Intent.ACTION_GET_CONTENT);
						cropAlbum.setType("image/*");
						cropAlbum.putExtra("crop", "true");
						cropAlbum.putExtra("aspectX", 1);
						cropAlbum.putExtra("aspectY", 1);
						cropAlbum.putExtra("outputX", 300);
						cropAlbum.putExtra("outputY", 300);
						cropAlbum.putExtra("scale", true);
						cropAlbum.putExtra("return-data", false);
						cropAlbum.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						cropAlbum.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
						startActivityForResult(cropAlbum,RESULT_CODE_ALBUM);
					}
				}
				
			});
		}break;
		case R.id.back:{
			if(animPlaying)
				return;
			if(editMode){
				quitEditConfirmation();			
			}else{
				finish();
			}
		}break;
		case R.id.commit:{
			if(animPlaying)
				return;
			if(!editMode){
				editMode = true;
				enterEditMode(true);
			}else{
				String nick = mNick.getText().toString();
				int igen = mGender.getSelectedItemPosition();
				String sgen = (igen == 1)?"f":"m";
				//String city = mCity.getText().toString();
				
				String addr = mAddress.getText().toString();
				int iedu = mEducation.getSelectedItemPosition() + 1;
				String sedu = String.valueOf(iedu);
				
				JSONObject commit = mData;
				try {
					commit.put("nick", nick);
					commit.put("gender", sgen);
					commit.put("addr", addr);
					commit.put("edu", sedu);
					commit.put("city", "");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					commit = null;
				}
				if(commit == null){
					mApp.showAlertDialog(this, R.string.sys_err);
					break;
				}
				
				boolean ok = mApp.getDataManager().commitData(DataManager.F_USERDATA, commit);
				if(ok){
					mApp.showWaitting(this, null);
				}else{
					mApp.showAlertDialog(UserDetailActivity.this, R.string.commit_err);
				}
			}
		}break;
		}
	}
	
	private int RESULT_CODE_ALBUM = 21;
	private int RESULT_CODE_CAMERA = 22;
	private int RESULT_CODE_CROP_CAMERA = 23;
	
	@Override
	public void onActivityResult(int requestCode, int result, Intent intent){
		if((RESULT_CODE_ALBUM == requestCode) || (RESULT_CODE_CROP_CAMERA == requestCode)){
			if(RESULT_OK == result){
				String path = mApp.getUploadFaceFileName();
				if(path == null)
					return;
				File f = new File(path);
				if(f.exists()){
					boolean ok = mApp.getDataManager().commitData(DataManager.F_USERFACE, path);
					
					if(ok){
						mApp.showWaitting(this, null);
					}else{
						mApp.showAlertDialog(UserDetailActivity.this, R.string.upPhoto_err);
					}
				}
			}
		}else if(RESULT_CODE_CAMERA == requestCode){
			if(RESULT_OK == result){
				String precrop = mApp.getUploadFacePreCropFileName();
				String path = mApp.getUploadFaceFileName();
				if((precrop == null) || (path == null))
					return;
				
				Uri preCropUri = Uri.parse("file://" + precrop);
				Uri imageUri = Uri.parse("file://" + path);
				Intent cropIntent = new Intent("com.android.camera.action.CROP");
				cropIntent.setDataAndType(preCropUri, "image/*");
				cropIntent.putExtra("crop", "true");//可裁剪
				cropIntent.putExtra("aspectX", 1);
				cropIntent.putExtra("aspectY", 1);
				cropIntent.putExtra("outputX", 300);
				cropIntent.putExtra("outputY", 300);
				cropIntent.putExtra("scale", true);
				cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				cropIntent.putExtra("return-data", false);//若为false则表示不返回数据
				cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
				//cropIntent.putExtra("noFaceDetection", true); 
				startActivityForResult(cropIntent, RESULT_CODE_CROP_CAMERA);
			}
		}
	}
}
